<template>
    <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <h2 class="text-center  margin-bottom" >{{title}}</h2>
            <a-form layout="inline" @keyup.enter.native="searchQuery">
                <a-row :gutter="24">

                    <a-col :md="6" :sm="24">
                        <a-form-item label="提交时间" style="display: flex;">
                            <a-range-picker
                                    :show-time="{ format: 'HH:mm' }"
                                    :placeholder="['开始时间', '结束时间']"
                                    v-model="rangeTime"
                                    format="YYYY-MM-DD HH:mm"
                                    @change="handleDateChange"
                            />
                        </a-form-item>
                    </a-col>

                    <a-col :md="6" :sm="24" v-if="customerList.length <= 0">
                        <a-form-item label="机构名称">
                            <a-input v-model="queryParam.customerName" placeholder="机构名称"/>
                        </a-form-item>
                    </a-col>

                    <a-col :md="8" :sm="24" v-if="(customerList.length <= 0) && (showSelectArea)" >
                        <a-form-item label="区域查询">
                            <select-area ref="selectAreaRef" @change="changeArea" ></select-area>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>

        <!-- 查询区域-END -->
        <div class="table-operator" style="display: flex;justify-content: space-between;align-items: center;">
            <div>
                <a-button type="primary" @click="searchQuery" icon="search">查询数据列表</a-button>
                <a-button type="primary" @click="resetForm">重置查询</a-button>
            </div>
            <div>
                <a-button type="primary" icon="printer" v-print="'#printTableList'">打印</a-button>
                <a-button type="primary" icon="download" @click="handleMwExportXlsForImages" v-if="customerList.length <= 0">
                    导出Excel
                </a-button>
            </div>
        </div>

        <!-- table区域-begin -->
        <div>
            <CheckboxWasteType @change="changeWasteType"></CheckboxWasteType>
        </div>

        <!-- table区域-begin -->

        <div>
            <a-table
                    ref="table"
                    size="middle"
                    bordered
                    rowKey="id"
                    :columns="columns"
                    :dataSource="dataSource"
                    :pagination="ipagination"
                    :loading="loading"
                    class="j-table-force-nowrap"
                    @change="handleTableChange"
            >
                <template slot="htmlSlot" slot-scope="text">
                    <div v-html="text"></div>
                </template>
                <template slot="imgSlot" slot-scope="text">
                    <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
                    <img v-else :src="text" height="25px" alt style="width: auto;height: 50px;"/>
                </template>
            </a-table>
        </div>

        <div v-show="false">
            <div id="printTableList">
                <h2 style="text-align: center;font-weight: bold;">各个机构提交废物数据统计</h2>
                <h3 v-if="rangeTime.length">时间 ： {{rangeTime[0]}} 至 {{rangeTime[1]}}</h3>
                <a-table
                        size="small"
                        bordered
                        rowKey="id"
                        :columns="printColumns"
                        :dataSource="dataSource"
                        :pagination="false"
                >
                    <template slot="htmlSlot" slot-scope="text">
                        <div style="color: black !important;" v-html="text"></div>
                    </template>

                </a-table>
            </div>
        </div>

        <jg-recycle-day-data-form ref="openInfo"></jg-recycle-day-data-form>
    </a-card>
</template>

<script>
    /**
     * create by Jane
     */
    import '@/assets/less/TableExpand.less'
    import { mixinDevice } from '@/utils/mixin'
    import { JeecgListMixin } from '@/mixins/JeecgListMixin'
    import SelectArea from '@/components/Jane/SelectArea'

    import { downloadFile } from '@/api/manage' // 模糊下拉查询
    import JgRecycleDayDataForm from './modules/JgRecycleDayDataForm'
    import CheckboxWasteType from '@/components/Jane/CheckboxWasteType'
    import * as user from '@/api/user'
    import { checkOnlyUser } from '@api/api'

    export default {
        mixins: [JeecgListMixin, mixinDevice],
        components: {
            SelectArea,
            JgRecycleDayDataForm,
            CheckboxWasteType,
        },
        data() {
            return {
                title : '各个机构提交废物数据统计',
                rangeTime: [],
                queryParam:{
                    creatTimeBegin : null,
                    creatTimeEnd : null,
                },
                // 表头
                columns: [],
                printColumns: [],
                url: {
                    list: null,
                    exportXlsUrlOkForImages: '/hc/Regulatory/exportCustomerBySupervise'
                },
                wasteTypeStatistic: [], // 废物分类数据统计
                wasteTypeList: [], // 废物类型列表 (原始数据)
                wasteId: [], // 选择的废物
                customerList: [],
            }
        },
        mounted() {
        },
        computed: {
            showSelectArea: function() {
                let state = true
                let userInfo = this.$store.getters.userInfo
                if (userInfo.provinceCode && userInfo.cityCode && userInfo.areaCode) {
                    state = false
                }
                return state
            }
        },
        methods: {
            // 配置默认信息
            async initDictConfig(){
                let date = new Date();
                let time1 = new Date(date.setHours(0, 0, 0, 0)).Format('yyyy-MM-dd hh:mm')
                let time2 = new Date(date.setHours(0, 0, 0, 0) + (1000 * 60 * 60 * 24 - 1)).Format('yyyy-MM-dd hh:mm')
                this.queryParam.creatTimeBegin = time1;
                this.queryParam.creatTimeEnd = time2;
                this.rangeTime = [this.queryParam.creatTimeBegin, this.queryParam.creatTimeEnd];

                this.queryParam.customerName = '';
                this.queryParam.cityCode = '';
                this.queryParam.areaCode = '';


                let ref = this.$refs.selectAreaRef;
                if(ref && ref.clearSelectArea != undefined){
                    ref.clearSelectArea();
                }

                // 获取到用户登陆的信息
                let userInfo = this.$store.getters.userInfo;
                if(userInfo.cityCode){
                    this.queryParam.cityCode = userInfo.cityCode;
                }
                if(userInfo.areaCode){
                    this.queryParam.areaCode = userInfo.areaCode;
                }
                if (userInfo.companysId) {
                    this.queryParam.companysId = userInfo.companysId
                }
                if(userInfo.customerNumber){
                    this.queryParam.customerNumber = userInfo.customerNumber
                }
                let orgList = await user.getAllCustomerByUserId()
                if (orgList) {
                    this.customerList = orgList || []
                    if (orgList[0]) {
                        this.queryParam.customerNumber = orgList[0].customerNumber
                    }
                }
                this.setColumns()

            },
            // 重置筛选表单
            resetForm : function(){
                this.initDictConfig();
                this.searchQuery();
            },

            handleDateChange(value, dateString) {
                this.rangeTime = dateString;
                if (dateString[0]) {
                    this.queryParam.creatTimeBegin = dateString[0];
                }
                if (dateString[1]) {
                    this.queryParam.creatTimeEnd = dateString[1];
                }
            },
            // 设置表格头部信息
            setColumns() {
                let data = this.wasteTypeList
                let cols = []
                // 循环遍历所有的父级废物类型
                data.forEach((item, index) => {
                    if (item.wasteTypeName) {
                        let child = [];
                        // 遍历出所有的子级废物类型
                        (item['children'] || []).forEach((val, i) => {
                            // 在选中的废物类型wasteId中查找id相同的元素
                            let info = this.wasteId.find(v => v === val.id)
                            // 存在
                            if (info) {
                                // 塑料输液瓶（袋）、玻璃输液瓶（袋）单位换成kg
                                if(val.id == "1366228898901467138" || val.id == "1366274806234079234"){
                                    val.priceUnit = "kg"
                                }
                                // 在child添加
                                child.push({
                                    // 废物父级名称
                                    title: val.wasteTypeName,
                                    dataIndex: 'id',
                                    key: `${index}-${i}`,
                                    // 废物子集内容
                                    children: [
                                        {
                                            title: '袋数',
                                            align: 'center',
                                            dataIndex: 'id',
                                            key: `${index}-${i}-1-1`,
                                            customRender: function(vv, waste, index) {
                                                let info = (waste['maps']).find((v) => v.waste_type === val.id)
                                                if (info) {
                                                    return  `${info.bagNum || ''}`
                                                }
                                                return ' '
                                            }
                                        },
                                        {
                                            title: `产生量${val.priceUnit ? `(${val.priceUnit})` : ''}`,
                                            align: 'center',
                                            dataIndex: 'id',
                                            key: `${index}-${i}-1-2`,
                                            customRender: function(vv, waste, index) {
                                                let info = (waste['maps']).find((v) => v.waste_type === val.id)
                                                if (info) {
                                                    return `${info.wasteOriginalValue || ''}`
                                                }
                                                return ' '
                                            }
                                        }
                                    ]
                                })
                            }
                        })
                        if (child.length) {
                            let obj = {
                                title: item.wasteTypeName,
                                dataIndex: 'id',
                                key: `${index}`,
                                children: child
                            }
                            cols.push(obj)
                        }
                    }
                })
                this.columns = [
                    {
                        title: '序号',
                        dataIndex: 'id',
                        key: 'rowIndex',
                        width: 60,
                        align: 'center',
                        scopedSlots: { customRender: 'htmlSlot' },
                        customRender: (text, row, index) => {
                            const obj = {
                                children: parseInt(index) + 1,
                                attrs: {}
                            }
                            if (row.colSpan) {
                                obj.children = <div style="color:red;font-weight:600;" >合计</div>;
                                obj.attrs.colSpan = 3;
                            }
                            return obj
                        }
                    },
                    {
                        title: '机构名称',
                        align: 'center',
                        dataIndex: 'customerName',
                        key: 'customerName',
                        scopedSlots: { customRender: 'link' },
                        customRender: (value, row, index) => {
                            const obj = {
                                children: <span style="font-weight:600;color:#64EAFF;text-decoration:underline;cursor: pointer;"
                               onclick = {()  => this.openInfo(row) }>
                                {value}
                                </span>,
                                attrs: {}
                            }
                            if (row.colSpan) {
                                obj.attrs.colSpan = 0
                            }
                            return obj
                        }
                    },
                    ...cols
                ]
                this.printColumns = [
                    {
                        title: '序号',
                        dataIndex: 'id',
                        key: 'rowIndex',
                        width: 60,
                        align: 'center',
                        scopedSlots: { customRender: 'htmlSlot' },
                        customRender: (text, row, index) => {
                            const obj = {
                                children: parseInt(index) + 1,
                                attrs: {}
                            }
                            if (row.colSpan) {
                                obj.children = <div style="color:red;font-weight:600;" >合计</div>;
                                obj.attrs.colSpan = 3;
                            }
                            return obj
                        }
                    },
                    {
                        title: '机构名称',
                        align: 'center',
                        dataIndex: 'customerName',
                        key: 'customerName',
                        scopedSlots: { customRender: 'link' },
                        customRender: (value, row, index) => {
                            const obj = {
                                children: value,
                                attrs: {}
                            }
                            if (row.colSpan) {
                                obj.attrs.colSpan = 0
                            }
                            return obj
                        }
                    },
                    ...cols

                    // {
                    //     title: '操作',
                    //     dataIndex: 'id',
                    //     scopedSlots: { customRender: 'action' }
                    // }
                ]
            },
            async changeArea({ area,city }){
                if(city){
                    this.queryParam.cityCode = city;
                }
                if(area){
                    this.queryParam.areaCode = area;
                }
            },
            // 废物类型选择改变
            changeWasteType(info,wasteList) {
                this.wasteId = info.ids;
                this.queryParam.wasteId = info.ids.join(',');
                this.wasteTypeList = wasteList;
                this.url.list = '/hc/Regulatory/getStatisticalV2';
                this.setColumns()
            },
            searchQuery: function() {
                this.queryParam.wasteId = this.wasteId.join(',')
                this.loadData(1)
            },
            handleMwExportXlsForImages() {
                let param = { ...this.queryParam }
                let name = `各机构台账统计-${new Date().FormatDate()}.xls`;
                downloadFile(this.url.exportXlsUrlOkForImages, name, param);
            },
            // 传值给子组件
            openInfo(info){
                let ref = this.$refs.openInfo
                if (ref) {
                    if (this.rangeTime[0]) {
                        info.creatTimeBegin = this.rangeTime[0];
                    }
                    if (this.rangeTime[1]) {
                        info.creatTimeEnd = this.rangeTime[1];
                    }
                    ref.show(info, info.customerNumber, info.customerName, this.wasteId, this.wasteTypeList)
                }
            },
        }
    }
</script>
<style scoped>
    @import '~@assets/less/common.less';
</style>
